<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <header>
        <h1>个人健康管理系统</h1>
        <nav>
            <ul>
                <li><a th:href="@{/}">首页</a></li>
                <li><a th:href="@{/foods}">食物管理</a></li>
                <li><a th:href="@{/users}" class="active">用户管理</a></li>
                <li><a th:href="@{/dietplans}">膳食计划</a></li>
                <li><a th:href="@{/userhealthindices}">健康指标</a></li>
            </ul>
        </nav>
    </header>

    <main class="container">
        <h2>用户管理</h2>

        <!-- 添加用户表单 -->
        <h3>添加新用户</h3>
        <form id="addUserForm" action="/api/users" method="post">
            <div class="form-group"><label for="addUsername">用户名:</label><input type="text" id="addUsername" name="username" required></div>
            <div class="form-group"><label for="addPassword">密码:</label><input type="password" id="addPassword" name="password" required></div>
            <div class="form-group"><label for="addEmail">邮箱:</label><input type="email" id="addEmail" name="email" required></div>
            <div class="form-group"><label for="addDisplayName">昵称:</label><input type="text" id="addDisplayName" name="displayName"></div>
            <div class="form-group"><label for="addRole">角色:</label><input type="text" id="addRole" name="role"></div>
            <div class="form-group"><label for="addGender">性别:</label><input type="text" id="addGender" name="gender"></div>
            <div class="form-group"><label for="addAge">年龄:</label><input type="number" id="addAge" name="age"></div>
            <div class="form-group"><label for="addHeight">身高(cm):</label><input type="number" id="addHeight" name="height" step="0.1"></div>
            <div class="form-group"><label for="addWeight">体重(kg):</label><input type="number" id="addWeight" name="weight" step="0.1"></div>
            <div class="form-group"><label for="addPhone">电话:</label><input type="text" id="addPhone" name="phone"></div>
            <button type="submit" class="btn">添加用户</button>
        </form>

        <!-- 用户列表 -->
        <h3>所有用户</h3>
        <table id="userTable" class="styled-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>昵称</th>
                    <th>角色</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>身高(cm)</th>
                    <th>体重(kg)</th>
                    <th>电话</th>
                    <th>禁用</th>
                    <th>注册时间</th>
                    <th>最近登录</th>
                    <th>头像</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 用户数据将通过JavaScript加载 -->
            </tbody>
        </table>

        <!-- 编辑用户表单 (初始隐藏) -->
        <h3 id="editFormTitle" style="display: none;">编辑用户</h3>
        <form id="editUserForm" style="display: none;" action="" method="put">
            <input type="hidden" id="editId" name="id">
            <div class="form-group"><label for="editUsername">用户名:</label><input type="text" id="editUsername" name="username" required></div>
            <div class="form-group"><label for="editPassword">密码:</label><input type="password" id="editPassword" name="password"></div>
            <div class="form-group"><label for="editEmail">邮箱:</label><input type="email" id="editEmail" name="email" required></div>
            <div class="form-group"><label for="editDisplayName">昵称:</label><input type="text" id="editDisplayName" name="displayName"></div>
            <div class="form-group"><label for="editRole">角色:</label><input type="text" id="editRole" name="role"></div>
            <div class="form-group"><label for="editGender">性别:</label><input type="text" id="editGender" name="gender"></div>
            <div class="form-group"><label for="editAge">年龄:</label><input type="number" id="editAge" name="age"></div>
            <div class="form-group"><label for="editHeight">身高(cm):</label><input type="number" id="editHeight" name="height" step="0.1"></div>
            <div class="form-group"><label for="editWeight">体重(kg):</label><input type="number" id="editWeight" name="weight" step="0.1"></div>
            <div class="form-group"><label for="editPhone">电话:</label><input type="text" id="editPhone" name="phone"></div>
            <button type="submit" class="btn">保存更改</button>
            <button type="button" class="btn btn-danger" onclick="hideEditForm()">取消</button>
        </form>

    </main>

    <footer>
        <p>&copy; 2025 个人健康管理系统</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            fetchUsers();

            // 处理添加用户表单提交
            document.getElementById('addUserForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(event.target);
                const userData = Object.fromEntries(formData.entries());
                // 类型转换
                if (userData.age) userData.age = Number(userData.age);
                if (userData.height) userData.height = Number(userData.height);
                if (userData.weight) userData.weight = Number(userData.weight);
                fetch('/api/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(userData)
                })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 409) {
                            alert('用户名或邮箱已存在！');
                        } else {
                            response.text().then(msg => alert('添加用户失败: ' + msg));
                        }
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchUsers(); // 刷新列表
                    event.target.reset(); // 重置表单
                })
                .catch(error => console.error('添加用户失败:', error));
            });

            // 处理编辑用户表单提交
            document.getElementById('editUserForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const userId = document.getElementById('editId').value;
                const formData = new FormData(event.target);
                const userData = Object.fromEntries(formData.entries());
                // 类型转换
                if (userData.age) userData.age = Number(userData.age);
                if (userData.height) userData.height = Number(userData.height);
                if (userData.weight) userData.weight = Number(userData.weight);
                fetch(`/api/users/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(userData)
                })
                .then(response => {
                    if (!response.ok) {
                        response.text().then(msg => alert('更新用户失败: ' + msg));
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchUsers(); // 刷新列表
                    hideEditForm(); // 隐藏编辑表单
                })
                .catch(error => console.error('更新用户失败:', error));
            });
        });

        function fetchUsers() {
            fetch('/api/users')
                .then(response => response.json())
                .then(users => {
                    const tbody = document.querySelector('#userTable tbody');
                    tbody.innerHTML = ''; // 清空现有内容
                    users.forEach(user => {
                        const row = tbody.insertRow();
                        row.innerHTML = `
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.email}</td>
                            <td>${user.displayName}</td>
                            <td>${user.role}</td>
                            <td>${user.gender}</td>
                            <td>${user.age}</td>
                            <td>${user.height}</td>
                            <td>${user.weight}</td>
                            <td>${user.phone}</td>
                            <td>${user.banned ? '是' : '否'}</td>
                            <td>${new Date(user.createdAt).toLocaleString()}</td>
                            <td>${user.lastLoginTime ? new Date(user.lastLoginTime).toLocaleString() : '从未登录'}</td>
                            <td>${user.avatarUrl ? `<img src="${user.avatarUrl}" alt="Avatar" style="width: 50px; height: 50px;">` : '无'}</td>
                            <td>
                                <button class="btn" onclick="editUser(${user.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteUser(${user.id})">删除</button>
                            </td>
                        `;
                    });
                })
                .catch(error => console.error('获取用户列表失败:', error));
        }

        function editUser(id) {
            fetch(`/api/users/${id}`)
                .then(response => response.json())
                .then(user => {
                    document.getElementById('editId').value = user.id;
                    document.getElementById('editUsername').value = user.username;
                    document.getElementById('editEmail').value = user.email;
                    document.getElementById('editDisplayName').value = user.displayName;
                    document.getElementById('editRole').value = user.role;
                    document.getElementById('editGender').value = user.gender;
                    document.getElementById('editAge').value = user.age;
                    document.getElementById('editHeight').value = user.height;
                    document.getElementById('editWeight').value = user.weight;
                    document.getElementById('editPhone').value = user.phone;
                    
                    document.getElementById('editFormTitle').style.display = 'block';
                    document.getElementById('editUserForm').style.display = 'block';
                })
                .catch(error => console.error('获取用户详情失败:', error));
        }

        function hideEditForm() {
            document.getElementById('editFormTitle').style.display = 'none';
            document.getElementById('editUserForm').style.display = 'none';
            document.getElementById('editUserForm').reset();
        }

        function deleteUser(id) {
            if (confirm('确定要删除此用户吗？')) {
                fetch(`/api/users/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    fetchUsers(); // 刷新列表
                })
                .catch(error => console.error('删除用户失败:', error));
            }
        }
    </script>

    <style>
        .styled-table {
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 1em;
            min-width: 1200px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.08);
        }
        .styled-table thead tr {
            background-color: #4CAF50;
            color: #fff;
            text-align: left;
        }
        .styled-table th, .styled-table td {
            padding: 12px 15px;
            border: 1px solid #ddd;
        }
        .styled-table tbody tr {
            border-bottom: 1px solid #ddd;
        }
        .styled-table tbody tr:nth-of-type(even) {
            background-color: #f3f3f3;
        }
        .styled-table tbody tr:last-of-type {
            border-bottom: 2px solid #4CAF50;
        }
        .btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 6px 14px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
            font-size: 0.95em;
            transition: background 0.2s;
        }
        .btn:hover {
            background-color: #388e3c;
        }
        .btn-danger {
            background-color: #f44336;
        }
        .btn-danger:hover {
            background-color: #c62828;
        }
        .form-group {
            margin-bottom: 12px;
        }
        label {
            display: inline-block;
            width: 90px;
            font-weight: bold;
        }
        input[type="text"], input[type="email"], input[type="password"], input[type="number"] {
            padding: 6px;
            border: 1px solid #ccc;
            border-radius: 4px;
            width: 220px;
        }
        .container {
            max-width: 1300px;
            margin: 0 auto;
            background: #fff;
            padding: 30px 40px;
            border-radius: 10px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        }
        h2, h3 {
            color: #4CAF50;
        }
    </style>
</body>
</html> 